package yc.web.servlets;

import com.google.gson.Gson;
import yc.bean.PageBean;
import yc.dao.DBHelper;
import yc.web.model.JsonModel;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

public abstract class BaseServlet extends HttpServlet {
    protected DBHelper db = new DBHelper();
//    private <T> Method findSetMethod(String methodName, Class<T> c) {
//
//        Method[] ms=c.getDeclaredMethods();
//        for(   Method m:ms){
//            if(  methodName.equals( m.getName() )){
//                return m;
//            }
//        }
//        return null;
//    }
    protected <T> T parseObjectFromRequest(HttpServletRequest request,Class<T> cls) throws InstantiationException, IllegalAccessException, InvocationTargetException {
        //1.创建T
        T t=cls.newInstance();
        //取出request中所有的参数
        Map<String,String[]> parameterMap=request.getParameterMap();
        for (Map.Entry<String,String[]> entry:parameterMap.entrySet()){
            String key= entry.getKey();
            String value=entry.getValue()[0];//只考虑一个值的情况。
            //到cls中找"set"+key
            String methodname="set"+key.substring(0,1).toUpperCase()+key.substring(1);
            Method setMethod=findSetMethod(methodname,cls);
            if (setMethod==null){
                continue;
            }
            //激活setMethod
            setMethod.invoke(t,value);

        }
        return t;
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String op = req.getParameter("op"); //op=regFile
        JsonModel jm = new JsonModel(); //用来保存要运行后的信息  并  返回到前端
        try {
            if (op == null || "".equals(op)) {
                // out.println( "{code:0,error:'没有op参数'}"  );
                jm.setCode(0);
                jm.setError("op参数不能为空..");
                writeJson(jm,resp);
                return;
            }
            ///        反 射
            Method[] methods  = this.getClass().getDeclaredMethods();//取子类中的方法
            for (Method m:methods){
                if (  m.getName().equals(  op  )  ) {  // 判断有没有 regFile方法
                    m.invoke(this, req,  resp);//激活对应函数  regFile
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            jm.setCode(0);
            jm.setError(  e.getMessage()  );
            writeJson(jm,resp);
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        req.setCharacterEncoding("utf-8");
//        resp.setCharacterEncoding("utf-8");  // 响应流的编码
//        resp.setContentType("text/html;charset=utf-8");//将功能移动到CharacterFilter中实现

        super.service(req, resp);
    }

    //*** 后端传数据到前端  关键地方   ***    以json格式传数据到前端
    protected void writeJson(  JsonModel jm , HttpServletResponse resp) throws IOException {
        resp.setContentType("text/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        Gson g = new Gson();
        out.println(  g.toJson(  jm  )); ///后端 把 运行情况 以json类型传出到前端
        out.flush();
        out.close();
    }
    private static int getIntParameter(HttpServletRequest request, String paramName, int defaultValue) {
        String paramValue = request.getParameter(paramName);
        if (paramValue != null) {
            try {
                return Integer.parseInt(paramValue);
            } catch (NumberFormatException e) {
                // 处理异常情况，比如参数不是合法的整数
            }
        }
        return defaultValue;
    }
    //自己写的类
    protected <T> T parseObjectFromRequest1(HttpServletRequest request, Class<T> cls)
            throws InstantiationException, IllegalAccessException, InvocationTargetException {
        // 1. 创建T
        T t = cls.newInstance();
        // 取出request中所有的参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue()[0]; // 只考虑一个值的情况。
            // 到cls中找"set"+key
            String methodName = "set" + key.substring(0, 1).toUpperCase() + key.substring(1);
            Method setMethod = findSetMethod(methodName, cls);
            if (setMethod == null) {
                continue;
            }
            // 获取setter方法的参数类型
            Class<?> paramType = setMethod.getParameterTypes()[0];
            Object convertedValue = convertValue(value, paramType);
            // 激活setMethod
            setMethod.invoke(t, convertedValue);
        }
        return t;
    }

    private Method findSetMethod(String methodName, Class<?> cls) {
        for (Method method : cls.getMethods()) {
            if (method.getName().equals(methodName) && method.getParameterCount() == 1) {
                return method;
            }
        }
        return null;
    }

    private Object convertValue(String value, Class<?> targetType) {
        if (targetType == String.class) {
            return value;
        } else if (targetType == int.class || targetType == Integer.class) {
            return Integer.parseInt(value);
        } else if (targetType == long.class || targetType == Long.class) {
            return Long.parseLong(value);
        } else if (targetType == double.class || targetType == Double.class) {
            return Double.parseDouble(value);
        } else if (targetType == float.class || targetType == Float.class) {
            return Float.parseFloat(value);
        } else if (targetType == boolean.class || targetType == Boolean.class) {
            return Boolean.parseBoolean(value);
        }
        // 可以根据需要添加更多类型转换
        throw new IllegalArgumentException("Unsupported parameter type: " + targetType);

}
}
